//
//  NHTRouterTool.swift
//  TestIos
//
//  Created by liyadong on 2025/11/12.
//  Copyright © 2025 Liyadong. All rights reserved.
//

import UIKit
import QuartzCore

class NHTRouterTool: NSObject {
    
    /// 获取当前显示的 NavigationController
    @objc static func currentNavigationController() -> UINavigationController? {
        var window: UIWindow?
        
        // iOS 13+ 使用新的方式获取 window
        if #available(iOS 13.0, *) {
            if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
                window = windowScene.windows.first(where: { $0.isKeyWindow })
            }
        } else {
            // iOS 13 之前使用旧的方式
            window = UIApplication.shared.keyWindow
        }
        
        guard let keyWindow = window,
              let rootViewController = keyWindow.rootViewController else {
            return nil
        }
        
        // 如果 rootViewController 就是 NavigationController
        if let navController = rootViewController as? UINavigationController {
            return navController
        }
        
        // 查找当前显示的 ViewController
        var currentVC = rootViewController
        while let presentedVC = currentVC.presentedViewController {
            currentVC = presentedVC
        }
        
        // 如果当前 VC 有 navigationController
        if let navController = currentVC.navigationController {
            return navController
        }
        
        // 如果当前 VC 是 NavigationController
        if let navController = currentVC as? UINavigationController {
            return navController
        }
        
        return nil
    }
    
    /// 统一处理页面跳转和 completion 回调
    @objc static func pushViewController(_ viewController: UIViewController, with params: [String: Any]?) {
        guard let navController = currentNavigationController() else {
            print("⚠️ NHTRouterTool: 无法获取 NavigationController")
            return
        }
        
        // 检查是否有 completion 回调
        if let completion = params?[NHTRouterParameterCompletion] as? ((Any?) -> Void) {
            // 使用 CATransaction 在 push 动画完成后调用 completion
            CATransaction.begin()
            CATransaction.setCompletionBlock {
                completion(["status": "success", "viewController": viewController])
            }
            navController.pushViewController(viewController, animated: true)
            CATransaction.commit()
        } else {
            // 没有 completion，直接 push
            navController.pushViewController(viewController, animated: true)
        }
    }
}
